package com.ilikesoup.instant.monitor.core;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Predicate;

public class MonitorMethodSupport implements MonitorMethodISupport {

    private Map<Predicate<Method>, ChangeEventTrigger> methodFilters;

    public MonitorMethodSupport() {
        this.methodFilters = new LinkedHashMap<>();
    }

    public MonitorMethodSupport(Map<Predicate<Method>, ChangeEventTrigger> methodFilters) {
        this.methodFilters = new LinkedHashMap<>(methodFilters.size());
        this.methodFilters.putAll(methodFilters);
    }

    @Override
    public ChangeEventTrigger findTrigger(Method method) {
        for (Map.Entry<Predicate<Method>, ChangeEventTrigger> entry : methodFilters.entrySet()) {
            if(entry.getKey().test(method)) {
                return entry.getValue();
            }
        }
        return null;
    }

    public MonitorMethodSupport register(Predicate<Method> methodFilter, ChangeEventTrigger changeEventTrigger) {
        methodFilters.put(methodFilter, changeEventTrigger);
        return this;
    }

    public MonitorMethodSupport unregister(Predicate<Method> methodFilter) {
        methodFilters.remove(methodFilter);
        return this;
    }

}
